package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.search.dao.ApAssociateWordsDao;
import com.heima.search.pojos.ApAssociateWords;
import com.heima.search.service.ApAssociateWordsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.regex.Pattern;

@Service
@Slf4j
public class ApAssociateWordsServiceImpl implements ApAssociateWordsService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private ApAssociateWordsDao apAssociateWordsDao;

    /**
     * 搜索联想词
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto) {
        //1.todo 校验参数
        if(dto == null || StringUtils.isBlank(dto.getSearchWords())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.todo 根据联想词进行模糊查询
        //方案1： 使用正则表达式
        //Pattern pattern = Pattern.compile("^.*" + dto.getSearchWords() + ".*$");
        //Query query = new Query();
        //query.addCriteria(Criteria.where("associateWords").regex(pattern));
        //List<ApAssociateWords> apAssociateWords1 = mongoTemplate.find(query, ApAssociateWords.class);
        //3.todo 封装返回结果
        List<ApAssociateWords> allByAssociateWordsLike =
                apAssociateWordsDao.findAllByAssociateWordsLike(dto.getSearchWords());
        return ResponseResult.okResult(allByAssociateWordsLike);
    }
}
